'''
Created on Nov 27, 2012

@author: mmoran
'''
from tweepy.streaming import StreamListener, Stream
from tweepy.auth import OAuthHandler
from tweepy.api import API
import tweepy
import urllib2
import urllib
import json
import uuid

import settings

# BASE_URL = 'http://anti-bullying.appspot.com'
BASE_URL = 'http://localhost:8080'


class MyStreamListener(StreamListener):
    def __init__(self, follow, api=None):
        StreamListener.__init__(self, api=api)
        self.follow = follow
 
    def on_status(self, status):
        resp = urllib.urlopen(BASE_URL + '/backend/predict?%s'%urllib.urlencode({'text':status.text}))
        data = json.load(resp)
        print data
        if data['outputLabel'] != 'normal':
            code = uuid.uuid4()
            a_res = urllib.urlopen(BASE_URL + '/api/aggressor/'+status.author.screen_name+'/')
            a = json.load(a_res)
            if 'error' in a:
                res = urllib.urlopen(BASE_URL + '/api/aggressor/',urllib.urlencode({'screen_name': status.author.screen_name}))
                a = json.load(res)
            print a
            rank = 1
            if data['outputLabel'] == 'alto':
                rank = 3
            elif data['outputLabel'] == 'medio':
                rank = 2
            for user in status.entities['user_mentions']:
                if user['screen_name'] in self.follow:
                    args = {"text":status.text,
                            "rank":rank,
                            "o_id":self.follow[user['screen_name']],
                            "a_id":a['data']['a_id']}
                    resp = urllib.urlopen(BASE_URL + '/api/reports/', urllib.urlencode(args))
                    r = json.load(resp)
                    print r
                    data = {'text':status.text,
                        'code':r['data']['r_id'],
                        'level':rank,
                        'victims':user['screen_name'],
                        'scrapper':status.author.screen_name}
                    res = urllib.urlopen(BASE_URL + '/api/notify/',urllib.urlencode(data))
                    n = json.load(res)
                    print n

    def on_error(self, status_code):
        print "ERROR: ",status_code
 
    def on_limit(self, track):
        print "LIMIT: ", track
 
    def on_timeout(self):
        print "TIMEOUT!"

def filter_follow(follow):
    auth = OAuthHandler(consumer_key2, consumer_secret2)
    auth.set_access_token(access_token2, access_token_secret2)
    stream = Stream(auth, MyStreamListener())
    api = API(auth)
    #print 'start filter track ', ','.join(track)
    stream.filter(follow=follow)

def filter_track(follow):
    stream = Stream(settings.auth, MyStreamListener(follow))
    api = API(settings.auth)
    #print 'start filter track ', ','.join(track)
    stream.filter(track=follow.keys())


if __name__ == '__main__':
    resp = urllib.urlopen(BASE_URL + '/api/observables/')
    data = json.load(resp)
    follow = dict([(s['screen_name'],s['o_id']) for s in data['data']])
    print follow
    filter_track(follow)

